package cn.itsource.hrm.userdetails;

import cn.itsource.hrm.domain.LoginUser;
import cn.itsource.hrm.domain.Permission;
import cn.itsource.hrm.mapper.LoginUserMapper;
import cn.itsource.hrm.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = loginUserMapper.loadByUsername(username);
        if(loginUser == null){
            throw new UsernameNotFoundException("无效的用户名");
        }

        //构造权限-用户拥有权限
        //1 查询员工对应权限
        List<Permission> permissions =  permissionMapper.loadPermissionsByUserId(loginUser.getId());
        //2 并且转换为List<SimpleGrantedAuthority>
        //List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("admin"));
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Permission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getSn()) );
        }
        //封装UserDetails的子类User
        User user = new  User(loginUser.getUsername(),
                loginUser.getPassword(),authorities);
        return user;
    }
}
